class User:
    def __init__(self):
        self.id = None
        self.username = None
        self.age = 0
        self.sex = 0
        self.birthday = None
        self.last_login_time = None

    def __setattr__(self, key, value):
        # if key == "address":
        #     raise Exception("You can not set the attribute named " + key)
        self.__dict__[key] = value

    def __getattr__(self, item):
        return False

    def __delattr__(self, item):
        print("You are deleting the property:" + item)
        del self.__dict__[item]

    def __eq__(self, other):
        return self.id == other.id




class UserManager:
    def __init__(self):
        self.users = {}

    def addUser(self, user):
        """
        将一个用户保存在一个字典里，方便查找
        :param user:
        :return:
        """
        assert isinstance(user, User)
        self.users[user.username] = user

    def getUser(self, username):
        """
        根据用户名查找用户
        :param username:
        :return:
        """
        assert isinstance(username, str)
        return self.users[username]

    def __getitem__(self, item):
        assert isinstance(item, str)
        return self.users[item]

    def __setitem__(self, key, value):
        assert isinstance(key, str) and isinstance(value, User)
        self.users[key] = value

    def __delitem__(self, key):
        del self.users[key]

    def __call__(self, *args, **kwargs):
        print(args[0])

    def __contains__(self, item):
        if item in self.users:
            return True

        return False

    def __enter__(self):
        print("Enter the function")

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exit the function")

if __name__ == "__main__":
    import datetime

    u = User()
    u2 = User()
    manager = UserManager()

    u.username = "John"
    u2.username = "Jim"

    # 将用户添加到管理器中
    manager['John'] = u
    manager['Jim'] = u2

    # manager.addUser(u)
    # manager.addUser(u2)

    # ... ...
    # u = manager.getUser("John")
    # u.last_login_time = datetime.datetime.now()
    #
    u = manager["John"]
    print("The user is online now:" + u.username)

    # ...
    # del manager["John"]

    u = manager["Jim"]
    setattr(u, "address", "ChengDu City")
    print("The address is:" + u.address)

    u3 = User()
    setattr(u3, "new_property", "hello")

    # setattr(u, "logined", True)
    # logout
    # delattr(u, "logined")

    #
    # if u.logined:
    #     print("Online")
    # else:
    #     print("Offline")

    manager("nihao")
    if "John" in manager:
        print("John is here")

    with open("", "w") as fp:
        pass

    with manager:
        print("Good")